package com.ryder.petmatediarybackend.common.init;

import com.ryder.petmatediarybackend.common.enums.RoleLevelEnum;
import com.ryder.petmatediarybackend.module.auth.dto.RoleDTO;
import com.ryder.petmatediarybackend.module.auth.entity.SysPermission;
import com.ryder.petmatediarybackend.module.auth.entity.SysRole;
import com.ryder.petmatediarybackend.module.auth.service.SysPermissionService;
import com.ryder.petmatediarybackend.module.auth.service.SysRolePermissionService;
import com.ryder.petmatediarybackend.module.auth.service.SysRoleService;
import com.ryder.petmatediarybackend.module.auth.service.SysUserRoleService;
import com.ryder.petmatediarybackend.module.pet.entity.SysUser;
import com.ryder.petmatediarybackend.module.pet.entity.SysPetTagLibrary;
import com.ryder.petmatediarybackend.module.pet.service.SysUserService;
import com.ryder.petmatediarybackend.module.pet.service.SysPetTagLibraryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 描述：数据初始化器
 * 在应用启动时自动初始化角色和权限数据
 *
 * @author Ryder
 * @version 1.0
 * @since 1.0
 * 更新日期: 2025/10/26
 */
@Slf4j
@Component
public class DataInitializer implements CommandLineRunner {

    private final SysRoleService roleService;

    private final SysPermissionService permissionService;

    private final SysRolePermissionService rolePermissionService;

    private final SysUserService userService;

    private final SysUserRoleService userRoleService;

    private final PasswordEncoder passwordEncoder;

    private final SysPetTagLibraryService petTagLibraryService;

    public DataInitializer(SysRoleService roleService, SysPermissionService permissionService, SysRolePermissionService rolePermissionService, SysUserService userService, SysUserRoleService userRoleService, PasswordEncoder passwordEncoder, SysPetTagLibraryService petTagLibraryService) {
        this.roleService = roleService;
        this.permissionService = permissionService;
        this.rolePermissionService = rolePermissionService;
        this.userService = userService;
        this.userRoleService = userRoleService;
        this.passwordEncoder = passwordEncoder;
        this.petTagLibraryService = petTagLibraryService;
    }

    @Override
    public void run(String... args) {
        log.info("========== 开始初始化系统数据 ==========");

        // 1. 初始化角色（检查后插入，避免重复）
        initRoles();

        // 2. 初始化权限
        initPermissions();

        // 3. 给平台管理员角色绑定所有权限
        bindRolePermissions();

        // 4. 创建平台管理员用户
        initAdminUser();

        // 5. 创建测试用户
        initTestUsers();

        // 6. 初始化系统宠物标签库
        initPetTagLibrary();

        log.info("========== 系统数据初始化完成 ==========");
    }

    /**
     * 初始化角色
     */
    private void initRoles() {
        log.info("开始初始化角色...");
        int count = 0;

        // 使用 RoleLevelEnum 遍历创建角色
        for (RoleLevelEnum roleEnum : RoleLevelEnum.values()) {
            // 检查角色是否已存在（通过 code 查询）
            if (!roleService.existsByCode(roleEnum.getRoleCode())) {
                RoleDTO dto = new RoleDTO();
                dto.setCode(roleEnum.getRoleCode());
                dto.setName(roleEnum.getName());
                dto.setRoleType(roleEnum.getLevel());
                dto.setDescription(roleEnum.getDescription());
                roleService.addRole(dto);
                count++;
                log.info("创建角色: {} - {}", roleEnum.getRoleCode(), roleEnum.getName());
            }
        }

        log.info("角色初始化完成，新增 {} 个角色", count);
    }

    /**
     * 初始化权限
     */
    private void initPermissions() {
        log.info("开始初始化权限...");
        int count = 0;

        // 定义权限（直接插入数据库）
        List<SysPermission> permissions = Arrays.asList(
                // ==================== 角色管理权限 ====================
                createPermission("system:role:add", "新增角色", 2, "/admin/role/add", "POST"),
                createPermission("system:role:edit", "编辑角色", 2, "/admin/role/update", "PUT"),
                createPermission("system:role:delete", "删除角色", 2, "/admin/role/delete", "DELETE"),
                createPermission("system:role:view", "查看角色", 2, "/admin/role/list", "GET"),
                createPermission("system:role:permission:assign", "分配角色权限", 2, "/admin/role/permission/assign", "POST"),
                createPermission("system:role:permission:remove", "移除角色权限", 2, "/admin/role/permission/remove", "POST"),
                createPermission("system:role:permission:view", "查看角色权限", 2, "/admin/role/permission/list", "GET"),
                
                // ==================== 定时任务管理权限 ====================
                createPermission("task:blacklist:sync", "手动触发黑名单同步", 2, "/admin/task/sync-blacklist", "POST"),
                
                // ==================== 文件上传管理权限 - 宠物主人权限 ====================
                createPermission("file:user:avatar:upload", "上传用户头像", 2, "/upload/image", "POST"),
                createPermission("file:pet:avatar:upload", "上传宠物头像", 2, "/upload/image", "POST"),
                createPermission("file:pet:album:upload", "上传宠物相册", 2, "/upload/image", "POST"),
                createPermission("file:diary:image:upload", "上传日记图片", 2, "/upload/image", "POST"),
                createPermission("file:moment:image:upload", "上传动态图片", 2, "/upload/image", "POST"),
                createPermission("file:delete", "删除文件", 2, "/upload/image", "DELETE"),
                
                // ==================== 文件上传管理权限 - 店铺经营者权限 ====================
                createPermission("file:shop:qualification:upload", "上传店铺资质", 2, "/upload/image", "POST"),
                createPermission("file:shop:pet:upload", "上传店铺宠物照片", 2, "/upload/image", "POST"),
                createPermission("file:shop:product:upload", "上传店铺商品照片", 2, "/upload/image", "POST"),
                
                // ==================== 宠物档案管理权限 ====================
                createPermission("pet:profile:create", "创建宠物档案", 2, "/pet/create", "POST"),
                createPermission("pet:profile:view", "查看宠物档案", 2, "/pet/list", "GET"),
                createPermission("pet:profile:update", "更新宠物档案", 2, "/pet/update", "PUT"),
                createPermission("pet:profile:delete", "删除宠物档案", 2, "/pet/delete", "DELETE"),
                
                // ==================== 宠物标签权限 ====================
                createPermission("pet:tag:apply", "申请新标签", 2, "/pet/tag-application/apply", "POST"),
                createPermission("pet:tag:check", "检查申请权限", 2, "/pet/tag-application/can-apply", "GET"),
                createPermission("pet:tag:view", "查看已申请标签", 2, "/pet/tag-application/my-list", "GET"),
                
                // ==================== 社交动态权限 ====================
                createPermission("social:post:create", "发布动态", 2, "/social/post/create", "POST"),
                createPermission("social:post:view", "查看动态", 2, "/social/pet-circle/list", "GET"),
                createPermission("social:post:update", "更新动态", 2, "/social/post/update", "PUT"),
                createPermission("social:post:delete", "删除动态", 2, "/social/post/delete", "DELETE"),
                createPermission("social:post:like", "点赞动态", 2, "/social/post/like", "POST"),
                createPermission("social:post:unlike", "取消点赞", 2, "/social/post/unlike", "DELETE"),
                createPermission("social:post:forward", "转发动态", 2, "/social/post/forward", "POST"),
                
                // ==================== 健康管理权限（未来功能） ====================
                createPermission("pet:health:checkin", "健康打卡", 2, "/pet/health/checkin", "POST"),
                createPermission("pet:health:view", "查看打卡记录", 2, "/pet/health/list", "GET"),
                createPermission("pet:calendar:create", "创建日历事项", 2, "/pet/calendar/create", "POST"),
                createPermission("pet:calendar:view", "查看日历事项", 2, "/pet/calendar/list", "GET"),
                createPermission("pet:calendar:update", "更新日历事项", 2, "/pet/calendar/update", "PUT"),
                createPermission("pet:calendar:delete", "删除日历事项", 2, "/pet/calendar/delete", "DELETE"),
                createPermission("pet:growth:create", "创建成长记录", 2, "/pet/growth/create", "POST"),
                createPermission("pet:growth:view", "查看成长记录", 2, "/pet/growth/list", "GET"),
                createPermission("pet:growth:update", "更新成长记录", 2, "/pet/growth/update", "PUT"),
                createPermission("pet:growth:delete", "删除成长记录", 2, "/pet/growth/delete", "DELETE"),
                
                // ==================== 店铺预约权限（宠物主人） ====================
                createPermission("shop:appointment:create", "创建预约", 2, "/shop/appointment/create", "POST"),
                createPermission("shop:appointment:view", "查看我的预约", 2, "/shop/appointment/my-list", "GET"),
                createPermission("shop:appointment:cancel", "取消预约", 2, "/shop/appointment/cancel", "PUT"),
                
                // ==================== 店铺信息管理权限（店铺经营者） ====================
                createPermission("shop:info:create", "创建店铺", 2, "/shop/info/create", "POST"),
                createPermission("shop:info:view", "查看店铺信息", 2, "/shop/info/detail", "GET"),
                createPermission("shop:info:update", "更新店铺信息", 2, "/shop/info/update", "PUT"),
                createPermission("shop:info:delete", "删除店铺", 2, "/shop/info/delete", "DELETE"),
                
                // ==================== 店铺宠物合集权限（店铺经营者） ====================
                createPermission("shop:pet:create", "添加店铺宠物", 2, "/shop/pet/create", "POST"),
                createPermission("shop:pet:view", "查看店铺宠物", 2, "/shop/pet/list", "GET"),
                createPermission("shop:pet:update", "更新店铺宠物", 2, "/shop/pet/update", "PUT"),
                createPermission("shop:pet:delete", "删除店铺宠物", 2, "/shop/pet/delete", "DELETE"),
                
                // ==================== 店铺商品合集权限（店铺经营者） ====================
                createPermission("shop:product:create", "添加店铺商品", 2, "/shop/product/create", "POST"),
                createPermission("shop:product:view", "查看店铺商品", 2, "/shop/product/list", "GET"),
                createPermission("shop:product:update", "更新店铺商品", 2, "/shop/product/update", "PUT"),
                createPermission("shop:product:delete", "删除店铺商品", 2, "/shop/product/delete", "DELETE"),
                
                // ==================== 公开查看店铺合集权限（所有用户） ====================
                createPermission("shop:collection:pet:public:view", "公开查看店铺宠物合集", 2, "/shop/collection/pet/shop/*", "GET"),
                createPermission("shop:collection:product:public:view", "公开查看店铺商品合集", 2, "/shop/collection/product/shop/*", "GET"),
                createPermission("shop:info:public:view", "公开查看店铺信息", 2, "/shop/nearby", "GET"),
                createPermission("shop:info:public:list", "公开查看店铺列表", 2, "/shop/list", "GET"),
                createPermission("shop:info:public:detail", "公开查看店铺详情", 2, "/shop/detail/*", "GET"),
                
                // ==================== 店铺预约管理权限（店铺经营者） ====================
                createPermission("shop:appointment:manage", "管理预约", 2, "/shop/appointment/list", "GET"),
                createPermission("shop:appointment:confirm", "确认预约", 2, "/shop/appointment/confirm", "PUT"),
                createPermission("shop:appointment:reject", "拒绝预约", 2, "/shop/appointment/reject", "PUT"),
                createPermission("shop:appointment:complete", "完成预约", 2, "/shop/appointment/complete", "PUT"),
                
                // ==================== 店铺资质管理权限（店铺经营者） ====================
                createPermission("shop:qualification:view", "查看资质", 2, "/shop/qualification/list", "GET"),
                createPermission("shop:qualification:submit", "提交资质", 2, "/shop/qualification/submit", "POST"),
                createPermission("shop:qualification:update", "更新资质", 2, "/shop/qualification/update", "PUT"),
                
                // ==================== 审核管理权限（平台管理员） ====================
                // 综合审核列表
                createPermission("audit:list", "查看所有待审核项目", 2, "/admin/audit/pending/all", "GET"),
                
                // 店铺资质审核
                createPermission("audit:qualification:list", "查看待审核店铺资质列表", 2, "/admin/audit/pending/qualifications", "GET"),
                createPermission("audit:qualification:approve", "审核店铺资质", 2, "/admin/audit/qualification", "POST"),
                
                // 店铺申请审核
                createPermission("audit:shop:list", "查看待审核店铺申请列表", 2, "/admin/audit/pending/shops", "GET"),
                createPermission("audit:shop:approve", "审核店铺申请", 2, "/admin/audit/shop", "POST"),
                
                // 宠物合集审核
                createPermission("audit:pet:list", "查看待审核宠物合集列表", 2, "/admin/audit/pending/pets", "GET"),
                createPermission("audit:pet:approve", "审核宠物合集", 2, "/admin/audit/pet", "POST"),
                
                // 商品合集审核
                createPermission("audit:product:list", "查看待审核商品合集列表", 2, "/admin/audit/pending/products", "GET"),
                createPermission("audit:product:approve", "审核商品合集", 2, "/admin/audit/product", "POST"),
                
                // 说说审核
                createPermission("audit:post:list", "查看待审核说说列表", 2, "/admin/audit/pending/posts", "GET"),
                createPermission("audit:post:approve", "审核说说", 2, "/admin/audit/post", "POST"),
                
                // 标签审核（预留）
                createPermission("audit:tag:view", "查看标签申请", 2, "/admin/audit/tag/list", "GET"),
                createPermission("audit:tag:approve", "审核通过标签", 2, "/admin/audit/tag/approve", "POST"),
                createPermission("audit:tag:reject", "驳回标签申请", 2, "/admin/audit/tag/reject", "POST"),
                
                // ==================== 标签库管理权限（平台管理员） ====================
                createPermission("pet:tag:library:create", "创建系统标签", 2, "/admin/tag-library/create", "POST"),
                createPermission("pet:tag:library:update", "更新系统标签", 2, "/admin/tag-library/update", "PUT"),
                createPermission("pet:tag:library:delete", "删除系统标签", 2, "/admin/tag-library/delete", "DELETE"),
                createPermission("pet:tag:library:manage", "管理系统标签", 2, "/admin/tag-library/list", "GET"),
                
                // ==================== 用户管理权限（平台管理员） ====================
                createPermission("admin:user:view", "查看用户列表", 2, "/admin/user/page", "GET"),
                createPermission("admin:user:edit", "编辑用户信息", 2, "/admin/user/update", "PUT"),
                createPermission("admin:user:delete", "删除用户", 2, "/admin/user/delete", "DELETE"),
                createPermission("admin:user:status", "修改用户状态", 2, "/admin/user/status", "PUT"),
                createPermission("admin:user:role:assign", "分配用户角色", 2, "/admin/user/role/assign", "POST"),
                createPermission("admin:user:role:remove", "移除用户角色", 2, "/admin/user/role/remove", "POST"),
                
                // ==================== 数据统计权限（平台管理员） ====================
                createPermission("stats:dashboard", "查看统计面板", 2, "/admin/stats/dashboard", "GET"),
                createPermission("stats:user", "查看用户统计", 2, "/admin/stats/user", "GET"),
                createPermission("stats:pet", "查看宠物统计", 2, "/admin/stats/pet", "GET"),
                createPermission("stats:shop", "查看店铺统计", 2, "/admin/stats/shop", "GET"),
                createPermission("stats:post", "查看动态统计", 2, "/admin/stats/post", "GET"),
                
                // ==================== 用户个人信息管理权限 ====================
                createPermission("user:profile:view", "查看个人信息", 2, "/user/profile/detail", "GET"),
                createPermission("user:profile:update", "更新个人信息", 2, "/user/profile/update", "PUT"),
                createPermission("user:profile:avatar", "上传头像", 2, "/user/profile/avatar", "POST"),
                createPermission("user:profile:password", "修改密码", 2, "/user/profile/change-password", "POST")
        );

        // 检查后插入
        for (SysPermission permission : permissions) {
            if (!permissionService.existsByCode(permission.getCode())) {
                permissionService.save(permission);
                count++;
                log.info("创建权限: {} - {}", permission.getCode(), permission.getName());
            }
        }

        log.info("权限初始化完成，新增 {} 个权限", count);
    }

    /**
     * 创建权限对象
     */
    private SysPermission createPermission(String code, String name, Integer permissionType, String path, String method) {
        SysPermission permission = new SysPermission();
        permission.setCode(code);
        permission.setName(name);
        permission.setType(permissionType);
        permission.setPath(path);
        permission.setMethod(method);
        permission.setStatus(1);
        return permission;
    }

    /**
     * 绑定角色权限
     */
    private void bindRolePermissions() {
        log.info("开始绑定角色权限...");

        // 1. 绑定平台管理员权限（所有权限）
        bindPlatformAdminPermissions();
        
        // 2. 绑定宠物主人权限（文件上传相关）
        bindPetOwnerPermissions();
        
        // 3. 绑定店铺经营者权限（文件上传相关）
        bindShopOwnerPermissions();
    }

    /**
     * 绑定平台管理员权限（所有权限）
     */
    private void bindPlatformAdminPermissions() {
        log.info("开始绑定平台管理员权限...");

        // 查询平台管理员角色
        SysRole platformAdminRole = roleService.getByCode(RoleLevelEnum.PLATFORM_ADMIN.getRoleCode());
        if (platformAdminRole == null) {
            log.warn("平台管理员角色不存在，跳过权限绑定");
            return;
        }

        // 查询所有权限
        List<SysPermission> allPermissions = permissionService.listAllPermissions();
        if (allPermissions.isEmpty()) {
            log.warn("没有可用权限，跳过权限绑定");
            return;
        }

        // 查询已绑定的权限ID
        List<Long> existingPermissionIds = rolePermissionService.getPermissionIdsByRoleId(platformAdminRole.getId());
        
        // 如果没有已绑定的权限，说明是第一次绑定，直接绑定所有权限
        if (existingPermissionIds.isEmpty()) {
            List<Long> allPermissionIds = allPermissions.stream()
                    .map(SysPermission::getId)
                    .collect(Collectors.toList());
            rolePermissionService.assignPermissions(platformAdminRole.getId(), allPermissionIds);
            log.info("平台管理员权限绑定完成，共绑定 {} 个权限", allPermissionIds.size());
            return;
        }
        
        // 查询已绑定的权限对象（根据ID）
        List<SysPermission> existingPermissions = permissionService.listByIds(existingPermissionIds);
        
        // 获取已绑定的权限code集合
        Set<String> existingPermissionCodes = existingPermissions.stream()
                .map(SysPermission::getCode)
                .collect(Collectors.toSet());
        
        // 过滤出未绑定的权限（根据code判断）
        List<Long> newPermissionIds = allPermissions.stream()
                .filter(perm -> !existingPermissionCodes.contains(perm.getCode()))
                .map(SysPermission::getId)
                .collect(Collectors.toList());
        
        if (newPermissionIds.isEmpty()) {
            log.info("平台管理员权限已全部绑定，跳过");
            return;
        }

        // 只绑定新增的权限
        rolePermissionService.assignPermissions(platformAdminRole.getId(), newPermissionIds);
        log.info("平台管理员权限绑定完成，新增 {} 个权限", newPermissionIds.size());
    }

    /**
     * 绑定宠物主人权限
     */
    private void bindPetOwnerPermissions() {
        log.info("开始绑定宠物主人权限...");

        // 查询宠物主人角色
        SysRole petOwnerRole = roleService.getByCode(RoleLevelEnum.PET_OWNER.getRoleCode());
        if (petOwnerRole == null) {
            log.warn("宠物主人角色不存在，跳过权限绑定");
            return;
        }

        // 定义宠物主人需要的权限code
        List<String> permissionCodes = Arrays.asList(
                // 文件上传权限
                "file:user:avatar:upload",
                "file:pet:avatar:upload",
                "file:pet:album:upload",
                "file:diary:image:upload",
                "file:moment:image:upload",
                "file:delete",
                
                // 宠物档案管理权限
                "pet:profile:create",
                "pet:profile:view",
                "pet:profile:update",
                "pet:profile:delete",
                
                // 宠物标签权限
                "pet:tag:apply",
                "pet:tag:check",
                "pet:tag:view",
                
                // 社交动态权限
                "social:post:create",
                "social:post:view",
                "social:post:update",
                "social:post:delete",
                "social:post:like",
                "social:post:unlike",
                "social:post:forward",
                
                // 健康管理权限
                "pet:health:checkin",
                "pet:health:view",
                "pet:calendar:create",
                "pet:calendar:view",
                "pet:calendar:update",
                "pet:calendar:delete",
                "pet:growth:create",
                "pet:growth:view",
                "pet:growth:update",
                "pet:growth:delete",
                
                // 店铺预约权限
                "shop:appointment:create",
                "shop:appointment:view",
                "shop:appointment:cancel",
                
                // 公开查看店铺权限
                "shop:collection:pet:public:view",
                "shop:collection:product:public:view",
                "shop:info:public:view",
                "shop:info:public:list",
                "shop:info:public:detail",
                
                // 用户个人信息管理权限
                "user:profile:view",
                "user:profile:update",
                "user:profile:avatar",
                "user:profile:password"
        );

        // 绑定权限
        bindPermissionsByCode(petOwnerRole.getId(), permissionCodes, "宠物主人");
    }

    /**
     * 绑定店铺经营者权限
     */
    private void bindShopOwnerPermissions() {
        log.info("开始绑定店铺经营者权限...");

        // 查询店铺经营者角色
        SysRole shopOwnerRole = roleService.getByCode(RoleLevelEnum.SHOP_OWNER.getRoleCode());
        if (shopOwnerRole == null) {
            log.warn("店铺经营者角色不存在，跳过权限绑定");
            return;
        }

        // 定义店铺经营者需要的权限code
        // 注意：宠物主人的权限由 ROLE_PET_OWNER 角色提供，店铺经营者会同时拥有两个角色
        List<String> permissionCodes = Arrays.asList(
                // 文件上传权限（店铺专用）
                "file:shop:qualification:upload",
                "file:shop:pet:upload",
                "file:shop:product:upload",
                
                // 店铺信息管理权限
                "shop:info:create",
                "shop:info:view",
                "shop:info:update",
                "shop:info:delete",
                
                // 店铺宠物合集权限
                "shop:pet:create",
                "shop:pet:view",
                "shop:pet:update",
                "shop:pet:delete",
                
                // 店铺商品合集权限
                "shop:product:create",
                "shop:product:view",
                "shop:product:update",
                "shop:product:delete",
                
                // 店铺预约管理权限
                "shop:appointment:manage",
                "shop:appointment:confirm",
                "shop:appointment:reject",
                "shop:appointment:complete",
                
                // 店铺资质管理权限
                "shop:qualification:view",
                "shop:qualification:submit",
                "shop:qualification:update",
                
                // 公开查看店铺权限（与宠物主人共享）
                "shop:collection:pet:public:view",
                "shop:collection:product:public:view",
                "shop:info:public:view",
                "shop:info:public:list",
                "shop:info:public:detail"
        );

        // 绑定权限
        bindPermissionsByCode(shopOwnerRole.getId(), permissionCodes, "店铺经营者");
    }

    /**
     * 根据权限code绑定权限
     */
    private void bindPermissionsByCode(Long roleId, List<String> permissionCodes, String roleName) {
        // 查询所有权限
        List<SysPermission> allPermissions = permissionService.listAllPermissions();
        
        // 过滤出需要绑定的权限
        List<SysPermission> targetPermissions = allPermissions.stream()
                .filter(perm -> permissionCodes.contains(perm.getCode()))
                .collect(Collectors.toList());
        
        if (targetPermissions.isEmpty()) {
            log.warn("{}没有可绑定的权限，跳过", roleName);
            return;
        }

        // 查询已绑定的权限ID
        List<Long> existingPermissionIds = rolePermissionService.getPermissionIdsByRoleId(roleId);
        
        // 过滤出未绑定的权限
        List<Long> newPermissionIds = targetPermissions.stream()
                .map(SysPermission::getId)
                .filter(id -> !existingPermissionIds.contains(id))
                .collect(Collectors.toList());
        
        if (newPermissionIds.isEmpty()) {
            log.info("{}权限已全部绑定，跳过", roleName);
            return;
        }

        // 绑定新权限
        rolePermissionService.assignPermissions(roleId, newPermissionIds);
        log.info("{}权限绑定完成，新增 {} 个权限", roleName, newPermissionIds.size());
    }

    /**
     * 创建平台管理员用户（授予宠物主人、店铺经营者和平台管理员角色）
     */
    private void initAdminUser() {
        log.info("开始创建平台管理员用户...");

        // 检查用户是否已存在
        SysUser existingUser = userService.lambdaQuery()
                .eq(SysUser::getUsername, "ryder")
                .one();

        if (existingUser != null) {
            log.info("平台管理员用户已存在，跳过创建");
            // 检查是否已绑定指定角色
            bindSpecificRolesToUser(existingUser.getId());
            return;
        }

        // 创建用户
        SysUser adminUser = new SysUser();
        adminUser.setUsername("ryder");
        adminUser.setPasswordHash(passwordEncoder.encode("ABC123."));  // 使用 Argon2 加密密码
        adminUser.setNickname("Ryder");
        adminUser.setPhone("15023264826");
        adminUser.setEmail("ran.yucheng@outlook.com");
        adminUser.setStatus(1);
        adminUser.setRegisterIp("127.0.0.1");

        userService.save(adminUser);
        log.info("平台管理员用户创建成功: {}", adminUser.getUsername());

        // 绑定指定角色
        bindSpecificRolesToUser(adminUser.getId());
    }

    /**
     * 给用户绑定指定角色（宠物主人、店铺经营者、平台管理员）
     */
    private void bindSpecificRolesToUser(Long userId) {
        log.info("开始为用户绑定指定角色...");

        // 定义需要绑定的角色
        List<String> roleCodes = Arrays.asList(
                RoleLevelEnum.PET_OWNER.getRoleCode(),
                RoleLevelEnum.SHOP_OWNER.getRoleCode(),
                RoleLevelEnum.PLATFORM_ADMIN.getRoleCode()
        );

        // 查询用户已有的角色ID
        List<Long> existingRoleIds = userRoleService.getRoleIdsByUserId(userId);

        // 绑定指定角色
        int bindCount = 0;
        for (String roleCode : roleCodes) {
            SysRole role = roleService.getByCode(roleCode);
            if (role == null) {
                log.warn("角色 {} 不存在，跳过绑定", roleCode);
                continue;
            }

            if (!existingRoleIds.contains(role.getId())) {
                userRoleService.bindUserRole(userId, role.getId());
                bindCount++;
                log.info("绑定角色: {} - {}", role.getCode(), role.getName());
            }
        }

        if (bindCount > 0) {
            log.info("用户角色绑定完成，共绑定 {} 个角色", bindCount);
        } else {
            log.info("用户已拥有指定角色，跳过绑定");
        }
    }

    /**
     * 初始化系统宠物标签库
     */
    private void initPetTagLibrary() {
        log.info("开始初始化系统宠物标签库...");
        int count = 0;

        // 定义标签数据
        List<SysPetTagLibrary> tags = Arrays.asList(
                // 性格类（1）
                createTag(1, "黏人精十级选手", 11),
                createTag(1, "高冷范拒人千里", 12),
                createTag(1, "戏精本精爱演", 13),
                createTag(1, "憨厚老实不记仇", 14),
                createTag(1, "警惕性超强小雷达", 15),
                
                // 爱好类（2）
                createTag(2, "霸占沙发C位", 13),
                createTag(2, "爱舔毛洁癖患者", 14),
                createTag(2, "玩水小狂魔", 15),
                createTag(2, "追飞虫小猎手", 16),
                createTag(2, "咬指甲解压", 17),
                createTag(2, "蹭家具做标记", 18),
                
                // 禁忌类（3）
                createTag(3, "忌喂食洋葱/大蒜", 11),
                createTag(3, "忌长时间暴晒", 12),
                createTag(3, "忌频繁洗澡破坏油脂", 13),
                createTag(3, "忌接触蚊香/杀虫剂", 14),
                createTag(3, "忌单独留车中", 15),
                
                // 精神状态类（4）
                createTag(4, "忧郁emo低气压", 11),
                createTag(4, "撒娇求关注蹭腿", 12),
                createTag(4, "烦躁甩头踱步", 13),
                createTag(4, "满足翻肚露肚皮", 14),
                createTag(4, "茫然四顾找主人", 15)
        );

        // 检查后插入
        for (SysPetTagLibrary tag : tags) {
            // 检查标签是否已存在（根据类型和名称）
            Long existingCount = petTagLibraryService.lambdaQuery()
                    .eq(SysPetTagLibrary::getTagType, tag.getTagType())
                    .eq(SysPetTagLibrary::getTagName, tag.getTagName())
                    .count();
            
            if (existingCount == 0) {
                petTagLibraryService.save(tag);
                count++;
                log.info("创建标签: [类型{}] {}", tag.getTagType(), tag.getTagName());
            }
        }

        log.info("系统宠物标签库初始化完成，新增 {} 个标签", count);
    }

    /**
     * 创建标签对象
     */
    private SysPetTagLibrary createTag(Integer tagType, String tagName, Integer sortOrder) {
        SysPetTagLibrary tag = new SysPetTagLibrary();
        tag.setTagType(tagType);
        tag.setTagName(tagName);
        tag.setSortOrder(String.valueOf(sortOrder));
        tag.setStatus(1);
        return tag;
    }

    /**
     * 创建测试用户
     */
    private void initTestUsers() {
        log.info("开始创建测试用户...");

        // 定义测试用户数据（用户名、昵称、角色列表）
        List<TestUserData> testUsers = Arrays.asList(
                new TestUserData("petmate_02", "宠物主人02", Arrays.asList(RoleLevelEnum.PET_OWNER.getRoleCode())),
                new TestUserData("petmate_03", "店铺经营者03", Arrays.asList(RoleLevelEnum.PET_OWNER.getRoleCode(), RoleLevelEnum.SHOP_OWNER.getRoleCode())),
                new TestUserData("petmate_04", "区域审核员04", Arrays.asList(RoleLevelEnum.PET_OWNER.getRoleCode(), RoleLevelEnum.REGIONAL_AUDITOR.getRoleCode())),
                new TestUserData("petmate_05", "区域管理员05", Arrays.asList(RoleLevelEnum.PET_OWNER.getRoleCode(), RoleLevelEnum.REGIONAL_MANAGER.getRoleCode()))
        );

        int createdCount = 0;
        for (TestUserData userData : testUsers) {
            // 检查用户是否已存在
            SysUser existingUser = userService.lambdaQuery()
                    .eq(SysUser::getUsername, userData.getUsername())
                    .one();

            if (existingUser != null) {
                log.info("测试用户 {} 已存在，跳过创建", userData.getUsername());
                // 确保已绑定指定角色
                bindRolesToUser(existingUser.getId(), userData.getRoleCodes(), userData.getUsername());
                continue;
            }

            // 创建用户
            SysUser testUser = new SysUser();
            testUser.setUsername(userData.getUsername());
            testUser.setPasswordHash(passwordEncoder.encode("ABC123."));  // 统一密码
            testUser.setNickname(userData.getNickname());
            testUser.setStatus(1);
            testUser.setRegisterIp("127.0.0.1");

            userService.save(testUser);
            createdCount++;
            log.info("创建测试用户成功: {} - {}", testUser.getUsername(), testUser.getNickname());

            // 绑定角色
            bindRolesToUser(testUser.getId(), userData.getRoleCodes(), userData.getUsername());
        }

        log.info("测试用户初始化完成，新增 {} 个用户", createdCount);
    }

    /**
     * 给用户绑定指定角色列表
     */
    private void bindRolesToUser(Long userId, List<String> roleCodes, String username) {
        // 查询用户已有的角色ID
        List<Long> existingRoleIds = userRoleService.getRoleIdsByUserId(userId);

        int bindCount = 0;
        for (String roleCode : roleCodes) {
            SysRole role = roleService.getByCode(roleCode);
            if (role == null) {
                log.warn("角色 {} 不存在，跳过绑定", roleCode);
                continue;
            }

            if (!existingRoleIds.contains(role.getId())) {
                userRoleService.bindUserRole(userId, role.getId());
                bindCount++;
                log.info("为用户 {} 绑定角色: {} - {}", username, role.getCode(), role.getName());
            }
        }

        if (bindCount > 0) {
            log.info("用户 {} 角色绑定完成，共绑定 {} 个角色", username, bindCount);
        } else {
            log.debug("用户 {} 已拥有所有指定角色", username);
        }
    }

    /**
     * 测试用户数据内部类
     */
    private static class TestUserData {
        private final String username;
        private final String nickname;
        private final List<String> roleCodes;

        public TestUserData(String username, String nickname, List<String> roleCodes) {
            this.username = username;
            this.nickname = nickname;
            this.roleCodes = roleCodes;
        }

        public String getUsername() {
            return username;
        }

        public String getNickname() {
            return nickname;
        }

        public List<String> getRoleCodes() {
            return roleCodes;
        }
    }
}
